package com.redxiii.spike.handlers;

import java.util.ArrayList;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.redxiii.spike.api.command.Command;
import com.redxiii.spike.api.command.MsgInterpreter;
import com.redxiii.spike.api.communication.CommunicationService;
import com.redxiii.spike.api.message.Message;
import com.redxiii.spike.util.command.CommandClassLoader;

/**
 * @author Daniel Filgueiras
 * @since Feb 21, 2013
 */
public abstract class AbstractXmlCommandHandler extends AbstractImHandler {

	private final Logger logger = LoggerFactory.getLogger(getClass());
	
	protected final List<MsgInterpreter> interpreters = new ArrayList<MsgInterpreter>();
	
	protected abstract String getXmlConfigFile();
	
	@Override
	public void init(CommunicationService service) {
		super.init(service);
		
		String configFile = getXmlConfigFile();
		if (configFile != null) {
			logger.debug("Loading commands from file: {}", configFile);
			
			CommandClassLoader loader = new CommandClassLoader(Thread.currentThread().getContextClassLoader(), configFile);
			interpreters.addAll(loader.createInterpreters());
		}
		
		logger.debug("Loaded {} message interpreters", interpreters.size());
	}

	protected Command interpret(Message message) {
		
		Command command = null;
		for (MsgInterpreter interpreter : interpreters) {
			command = interpreter.parseMessage(message);
			if (command != null)
				break;
		}
		
		return command;
	}

}
